package com.warm.system.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import com.warm.auth.helper.LoginHelper;
import com.warm.core.constant.Constants;
import com.warm.core.domain.AjaxResult;
import com.warm.core.domain.R;
import com.warm.core.utils.StreamUtils;
import com.warm.core.utils.StringUtils;
import com.warm.orm.domain.sys.SysMenu;
import com.warm.orm.domain.sys.SysTenant;
import com.warm.orm.domain.sys.SysUser;
import com.warm.system.api.model.LoginBody;
import com.warm.system.api.model.LoginTenantVo;
import com.warm.system.api.model.TenantListVo;
import com.warm.system.service.ISysMenuService;
import com.warm.system.service.ISysTenantService;
import com.warm.system.service.SysLoginService;
import com.warm.system.service.SysPermissionService;
import com.warm.tenant.helper.TenantHelper;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.validation.annotation.Valid;

import java.net.URL;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author warm
 */
@Valid
@Controller
public class SysLoginController {
    @Inject
    private SysLoginService loginService;

    @Inject
    private ISysMenuService menuService;

    @Inject
    private SysPermissionService permissionService;

    @Inject
    private ISysTenantService tenantService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @Post
    @Mapping("/login")
    public AjaxResult login(LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @Get
    @Mapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = LoginHelper.getUser();
        if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
            // 超级管理员 如果重新加载用户信息需清除动态租户
            TenantHelper.clearDynamic();
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @Get
    @Mapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 登出
     *
     * @return
     */
    @SaIgnore
    @Mapping("logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok();
    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @SaIgnore
    @Get
    @Mapping("/tenant/list")
    public R<LoginTenantVo> tenantList(Context ctx) throws Exception {
        if (!TenantHelper.isEnable()) {
            LoginTenantVo vo = new LoginTenantVo();
            vo.setTenantEnabled(TenantHelper.isEnable());
            return R.ok(vo);
        }
        List<SysTenant> tenantList = tenantService.selectList(new SysTenant());
        List<TenantListVo> voList = StreamUtils.toList(tenantList, (tenant) -> TenantListVo.builder()
                .tenantId(tenant.getTenantId()).domain(tenant.getDomain()).companyName(tenant.getCompanyName()).build());
        // 获取域名
        String host;
        String referer = ctx.header("referer");
        if (StringUtils.isNotBlank(referer)) {
            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
            host = referer.split("//")[1].split("/")[0];
        } else {
            host = new URL(ctx.url()).getHost();
        }
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo ->
                StringUtils.equals(vo.getDomain(), host));
        // 返回对象
        LoginTenantVo vo = new LoginTenantVo();
        vo.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        vo.setTenantEnabled(TenantHelper.isEnable());
        return R.ok(vo);
    }
}
